/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.border.EtchedBorder;

/**
 *
 * @author Administrator
 */
public class CreateFrame extends BaseFrame{
    protected List<Question> qs = new ArrayList<Question>();
//    protected List<JToggleButton> buttons = new ArrayList<JToggleButton>();
//    protected List<JTextField> opts = new ArrayList<JTextField>();
    protected List<Box> opts = new ArrayList<Box>();
    protected List<JButton> delete = new ArrayList<JButton>();
    protected JButton done,more;
    protected JRadioButton singleSelect,multSelect;
    protected Box select,opt;
    protected JTextArea desc;
    private JScrollPane Sdesc, Sopt;
    private ButtonGroup bg;
    private int i=0;
    private final Eventer evt = new Eventer();
    private final ImageIcon del = new ImageIcon(Prova.class.getResource("delete_icon.gif"));
    
    public CreateFrame() {
        super("You're such a nurd.");
        done = new JButton("It's done, Bitch!");
        done.setActionCommand("done");
        done.addActionListener(evt);
        
        bs.add(Box.createHorizontalStrut(5));
        bs.add(done);
        bs.add(Box.createHorizontalStrut(3));
        
        ButtonGroup bg = new ButtonGroup();
        singleSelect = new JRadioButton("Single Answer");
        singleSelect.setActionCommand("1"); // Question.Single_Selection = 1
        singleSelect.addActionListener(evt);
        bg.add(singleSelect);
        multSelect = new JRadioButton("Multiple Answers");
        multSelect.setActionCommand("2");  // Question.Multiple_Selection = 2
        multSelect.addActionListener(evt);
        bg.add(multSelect);
        singleSelect.setSelected(true);
        
        select = Box.createHorizontalBox();
        select.add(singleSelect);
        select.add(Box.createHorizontalGlue());
        select.add(multSelect);
        select.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GREEN, Color.GRAY), "Answer Type"));
        
        more = new JButton("Nova alternativa",new ImageIcon(Prova.class.getResource("more_icon.gif")));
        more.setActionCommand("new");
        more.addActionListener(evt);
        
        desc = new JTextArea();
        desc.setLineWrap(true);
        desc.setWrapStyleWord(true);
        desc.setRows(3);
        Sdesc = new JScrollPane(desc);
        Sdesc.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        Sdesc.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        Sdesc.getViewport().setMinimumSize(new Dimension(300,200));
        
        opt = Box.createVerticalBox();
        Sopt = new JScrollPane(opt);
        Sopt.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        Sopt.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        addQuestion();
        
        this.setVisible(true);
        this.setSize(500,500);
    }
    
    private void addQuestion() {
        quests.removeAll();
        opts.clear();
        delete.clear();
        bg = new ButtonGroup();
        quests.add(select);
        
        desc.setText("");
        quests.add(new JLabel("Título"));
        quests.add(Sdesc);
//        quests.add(Box.createVerticalStrut(100));
        opt.removeAll();
        quests.add(Sopt);
        quests.add(more);
        
        addOpt();
        
        this.validate();
        //mais.....
    }
    
    private void addQuestion(Question q) {
        quests.removeAll();
        opts.clear();
        delete.clear();
        bg = new ButtonGroup();
        quests.add(select);
        
        desc.setText(q.getDescription());
        quests.add(new JLabel("Título"));
        quests.add(Sdesc);
        opt.removeAll();
        quests.add(Sopt);
        quests.add(more);
        
        List<String> ls = q.getOptions(),lca = q.getCorrectAnswers();
        for(String s: ls) {
            addOpt();
            Box b = opts.get(opts.size()-1);
            ((JTextField) b.getComponent(1)).setText(s);
            if(lca.contains(s)) ((JToggleButton) b.getComponent(0)).setSelected(true);
        }
        
        this.validate();
    }
    
    private void addOpt() {
        try {
            Class<? extends JToggleButton> cl = (singleSelect.isSelected())? JRadioButton.class : JCheckBox.class;
            JToggleButton tb = cl.newInstance();
            if(cl==JRadioButton.class)
                bg.add(tb);
//            buttons.add(tb);
            JTextField tf = new JTextField();
            
//            opts.add(tf);
            JButton jb = new JButton(del);
            jb.setActionCommand("delete");
            jb.addActionListener(evt);
            delete.add(jb);
//            delete.add(jb);
            Box b = Box.createHorizontalBox();
            b.add(tb);
            b.add(tf);
            b.add(jb);
            opts.add(b);
            opt.add(b);
            
//            quests.validate();
//            Sopt.validate();
//            opt.validate();
            this.validate();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void loadNext() {
            if(desc.getText().isEmpty()) { warn("Você não colocou o enunciado!!!!"); return; }
            boolean aux = false;
            for(Box b : opts) {
                JToggleButton tb = (JToggleButton) b.getComponent(0);
                JTextField tf = (JTextField) b.getComponent(1);
                if(tb.isSelected()) aux = true;
                if(tf.getText().isEmpty()) { warn("Você deixou alguma alternativa sem escrever nada..."); return; }
            }
            if(!aux) { warn("Não há nenhuma alternativa selecionada!"); return; }
            
            List<String> lo = new ArrayList<String>();
            List<Integer> li = new ArrayList<Integer>();
            for (int j = 0; j < opts.size(); j++) {
            Box b = opts.get(j);
            lo.add(((JTextField) b.getComponent(1)).getText());
            if(((JToggleButton) b.getComponent(0)).isSelected())
                li.add(j);
            }
            Question q = new Question(desc.getText(),lo,li,(singleSelect.isSelected())?Question.Single_Selection:Question.Multiple_Selection);
            
            if(qs.size()>i) qs.set(i,q);
            else qs.add(q);
            JOptionPane.showMessageDialog(this, "Question saved!", "Oh yeah",JOptionPane.INFORMATION_MESSAGE);
            
            activateBack();
            ++i;
            if(qs.size()>i)  addQuestion(qs.get(i));
            else addQuestion();
//            System.out.println(qs);
    }

    @Override
    public void loadPrevious() {
        int ans = JOptionPane.showConfirmDialog(this, "You sure? This will delete anything you've changed in this question (unless it's been saved)", "I told you so!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if(ans==JOptionPane.CANCEL_OPTION) return;
//        --i;
        addQuestion(qs.get(--i));
        if(i==0) deactivateBack();
    }
    
    private void warn(String s) {
        JOptionPane.showMessageDialog(this, s, "Are you crazy?", JOptionPane.WARNING_MESSAGE);
    }
    
    private class Eventer implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = e.getActionCommand();
            if(s.equals("new")) addOpt();
            else if(s.equals("done")) {
                int ans = JOptionPane.showConfirmDialog(CreateFrame.this, "You will loose any unsaved Questions, if you want to save this one (and haven't already), create a new one (press forward), and then click finish again", "HEY!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                if(ans==JOptionPane.CANCEL_OPTION) return;
                JFileChooser fc = new JFileChooser();
                fc.setMultiSelectionEnabled(false);
                fc.showSaveDialog(CreateFrame.this);
                File f = fc.getSelectedFile();
                if(f.isDirectory()) { warn("You can't save to a directory!"); return; }
                if(f.exists()) {int anss = JOptionPane.showConfirmDialog(CreateFrame.this, "Are you sure you want to overwrite the file?", "HEY!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if(anss==JOptionPane.NO_OPTION) return; }
                PrintWriter out = FileManager.getWriter(f, false);
                
                StringBuilder sb = new StringBuilder();
                for(Question q:qs) 
                    sb.append(q.toString()).append(sep);
                sb.replace(sb.length()-sep.length(), sb.length() + 1, "");
                
                out.print(Prova.encode(sb.toString(),3));
                out.close();
                
                JOptionPane.showMessageDialog(CreateFrame.this, "It was saved!", "Bye-Bye", JOptionPane.INFORMATION_MESSAGE);
            }
            else if(s.equals("delete")) {
                int n = delete.indexOf(e.getSource());
                opt.remove(n);
                opts.remove(n);
                delete.remove(n);
            }else {
                int n = Integer.parseInt(s);
                bg =  new ButtonGroup();
                Class<? extends JToggleButton> cl = (n==1)? JRadioButton.class : JCheckBox.class;
                for(Box b : opts) {
                    try {
                        JToggleButton tb = cl.newInstance();
                        if(n==1) bg.add(tb);
                        b.remove(0);
                        b.add(tb, 0);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.exit(1);
                    }
                    
                }
            }
            
            quests.validate();
        }
        
        private static final String sep = "#3#";
        
    }
    
}
